package com.sogoodsoft.service.security;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import com.sogoodsoft.entity.account.SecurityUser;
import com.sogoodsoft.entity.account.User;
import com.sogoodsoft.entity.app.Organization;
import com.sogoodsoft.util.InfosysSecurityUtil;
import com.sogoodsoft.util.InfosysUtils;

public class AfterLoginFilter implements Filter {

	private static Log log = LogFactory.getLog(AfterLoginFilter.class); 
	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		//log.debug("AfterLoginFilter");
		HttpServletRequest req = (HttpServletRequest)request;
		Object obj = req.getSession().getAttribute("currUser");
		if(obj==null){
			log.debug("context.getAuthentication() instanceof Authentication :"+(SecurityContextHolder.getContext().getAuthentication() instanceof Authentication));
			User user = getCurrentUser();
			log.debug("currUser:"+user);
			if(user!=null){
				String root  = InfosysUtils.getOrgRoot(req);
				req.getSession().setAttribute("currUser", user);
				req.getSession().setAttribute("root", root);
				log.debug("set currUser user:"+user.getName());
			}
			
		}
		
		
		chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}
	
	
	public  User getCurrentUser(){
		User user = null;
		if(!(SecurityContextHolder.getContext().getAuthentication() instanceof Authentication)){
			return user;
		}
		Object obj = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		if(!obj.getClass().equals(String.class)){
			SecurityUser sUser = (SecurityUser)obj;
			user = sUser.getUser();
		}else{
			log.debug("currUser is not a User Object:"+obj);
		}
		
		return user;
	}

}
